package com.atguigu.orderservice.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.commonutils.R;
import com.atguigu.orderservice.entity.TOrder;
import com.atguigu.orderservice.entity.TPayLog;
import com.atguigu.orderservice.mapper.TOrderMapper;
import com.atguigu.orderservice.mapper.TPayLogMapper;
import com.atguigu.orderservice.service.TPayLogService;

import com.atguigu.orderservice.utils.HttpClient;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 支付日志表 服务实现类
 * </p>
 *
 * @author huangqicai
 * @since 2023-04-01
 */
@Service
public class TPayLogServiceImpl extends ServiceImpl<TPayLogMapper, TPayLog> implements TPayLogService {

    @Autowired
    private TOrderMapper tOrderMapper;

    /*根据订单信息生成微信二维码*/
    @Override
    public R createNative(String orderIdNo) {
        Map mapRes = null;
        try {
            /*1.根据订单id获取订单信息*/
            TOrder orderInfo = tOrderMapper.selectOne(new QueryWrapper<TOrder>().eq("order_no", orderIdNo));
            /*2.设置支付参数*/
            HashMap map = new HashMap<>();
            map.put("appid", "wx74862e0dfcf69954");
            map.put("mch_id", "1558950191");
            map.put("nonce_str", WXPayUtil.generateNonceStr());
            map.put("body", orderInfo.getCourseTitle());
            map.put("out_trade_no", orderIdNo);
            map.put("total_fee", orderInfo.getTotalFee().multiply(new BigDecimal("100")).longValue()+"");
            map.put("spbill_create_ip", "127.0.0.1");
            map.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify\n");
            map.put("trade_type", "NATIVE");
            /*3.HttpClient根据url访问第三方接口传递参数*/
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");

            //client设置参数
            client.setXmlParam(WXPayUtil.generateSignedXml(map,"T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            client.setHttps(true);
            client.post();
            //3、返回第三方的数据
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            //4、封装返回结果集

            mapRes = new HashMap<>();
            mapRes.put("out_trade_no", orderIdNo);
            mapRes.put("course_id", orderInfo.getCourseId());
            mapRes.put("total_fee", orderInfo.getTotalFee());
            mapRes.put("result_code", resultMap.get("result_code"));
            mapRes.put("code_url", resultMap.get("code_url"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.ok().data(mapRes);
    }


    /*根据订单idNo获取支付状态*/
    @Override
    public R queryPayStatus(String orderNo) {
        /*1.封装参数*/
        Map map = new HashMap<>();
        map.put("appid", "wx74862e0dfcf69954");
        map.put("mch_id", "1558950191");
        map.put("out_trade_no", orderNo);
        map.put("nonce_str", WXPayUtil.generateNonceStr());

        try {
            /*2.设置请求*/
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(map, "T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            client.setHttps(true);
            client.post();

            /*3.返回第三方的数据*/
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);

            if (resultMap == null) {//出错
                return R.error().message("支付出错");
            }
            if (resultMap.get("trade_state").equals("SUCCESS")) {//如果成功
                //更改订单状态
                updateOrderStatus(resultMap);
                return R.ok().message("支付成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return R.ok().code(25000).message("支付中");
    }



    /*更新订单状态*/
    public void updateOrderStatus(Map<String, String> map) {
        //获取订单id
        String orderNo = map.get("out_trade_no");
        //根据订单id查询订单信息
        QueryWrapper<TOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no",orderNo);
        TOrder order = tOrderMapper.selectOne(wrapper);

        if(order.getStatus().intValue() == 1) return;
        order.setStatus(1);
        tOrderMapper.updateById(order);

        //记录支付日志
        TPayLog payLog=new TPayLog();
        payLog.setOrderNo(order.getOrderNo());//支付订单号
        payLog.setPayTime(new Date());
        payLog.setPayType(1);//支付类型
        payLog.setTotalFee(order.getTotalFee());//总金额(分)
        payLog.setTradeState(map.get("trade_state"));//支付状态
        payLog.setTransactionId(map.get("transaction_id"));
        payLog.setAttr(JSONObject.toJSONString(map));
        baseMapper.insert(payLog);//插入到支付日志表
    }

}
